<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Cate",
  inheritAttrs: false,
});

import {
  addCate,
  deleteCate,
  getCateForm,
  getCateOptions,
  listCategories,
  updateCate,
} from "@/api/application/cate";
import { CateForm, CateQuery, CateVO } from "@/api/application/cate/types";

import IconSelect from "@/components/IconSelect/index.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";

import { onMounted, reactive, ref } from "vue";

const queryFormRef = ref(ElForm);
const cateFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive({
  title: "",
  visible: false,
});

const queryParams = reactive<CateQuery>({});
const cateList = ref<CateVO[]>([]);

const cateOptions = ref<OptionType[]>([]);

const formData = reactive<CateForm>({
  sort: 0,
  categoryName: "",
  isActive: true,
  icon: "",
});

const rules = reactive({
  parentId: [{ required: true, message: "请选择顶级类别", trigger: "blur" }],
  categoryName: [
    { required: true, message: "请输入类别名称", trigger: "blur" },
  ],
});

// 选择表格的行类别ID
const selectedRowCateId = ref<number | undefined>();

/**
 * 查询
 */
async function handleQuery() {
  // 重置父组件
  loading.value = true;
  try {
    const data = await listCategories(queryParams);

    cateList.value = data;
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  handleQuery();
}

/**行点击事件 */
function onRowClick(row: CateVO) {
  selectedRowCateId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父类别ID
 * @param cateId 类别ID
 */
async function openDialog(parentId?: number, cateId?: number) {
  const data = await getCateOptions();
  cateOptions.value = [{ value: 0, label: "顶级类别", children: data }];

  dialog.visible = true;
  if (cateId) {
    dialog.title = "编辑类别";
    const data = await getCateForm(cateId);
    Object.assign(formData, data);
  } else {
    dialog.title = "新增类别";
    formData.parentId = parentId;
  }
}

/** 类别保存提交 */
function submitForm() {
  cateFormRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      const cateId = formData.id;
      try {
        if (cateId) {
          await updateCate(cateId, formData);
          ElMessage.success("修改成功");
        } else {
          await addCate(formData);
          ElMessage.success("新增成功");
        }
      } catch (error) {
      } finally {
        closeDialog();
        handleQuery();
      }
    }
  });
}

/** 删除类别 */
function handleDelete(cateId: number) {
  if (!cateId) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteCate(cateId);
      ElMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  cateFormRef.value.resetFields();
  cateFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = 0;
  formData.sort = 1;
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="类别名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><template #icon><i-ep-search /></template>搜索</el-button
          >
          <el-button @click="resetQuery">
            <template #icon><i-ep-refresh /></template>
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['sys:category:create']"
          type="success"
          @click="openDialog(0)"
        >
          <template #icon><i-ep-plus /></template>
          新增</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        :data="cateList"
        highlight-current-row
        row-key="id"
        :expand-row-keys="['1']"
        @row-click="onRowClick"
        :tree-props="{
          children: 'subCate',
          hasChildren: 'hasChildren',
        }"
      >
        <!-- <el-table-column label="id" align="left" width="150" prop="id" /> -->

        <el-table-column label="类别名称" min-width="150">
          <template #default="scope">
            <svg-icon :icon-class="scope.row.icon" />
            {{ scope.row.categoryName }}
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" width="200">
          <template #default="scope">
            <el-tag v-if="scope.row.isActive" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="排序" align="center" width="300" prop="sort" />
        <el-table-column
          label="创建时间"
          align="left"
          width="300"
          prop="createTime"
        />
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.parentId === 0"
              v-hasPerm="['sys:category:create']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
            >
              <i-ep-plus />新增
            </el-button>

            <el-button
              v-hasPerm="['sys:category:update']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(undefined, scope.row.id)"
            >
              <i-ep-edit />编辑
            </el-button>
            <el-button
              v-hasPerm="['sys:category:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加类别 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      destroy-on-close
      append-to-body
      width="500px"
      @close="closeDialog"
      :draggable="true"
      top="5vh"
    >
      <el-form
        ref="cateFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="父级类别" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级类别"
            :data="cateOptions"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item required label="类别名称" prop="categoryName">
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入类别名称"
          />
        </el-form-item>

        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="formData.isActive" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="图标" prop="icon" v-if="formData.parentId === 0">
          <!-- 图标选择器 -->
          <icon-select v-model="formData.icon" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
